<?php

class EnrollAction extends Action {

	/**
	 * 获取报名人数列表
	 * @param $actId 活动id
	 * @param $nickname 搜索值
	 * @param $limit 查询偏移量
	 * @param $start  查询开始
	 * @param $order  排序字段
	 * @param $by  排序规则
	 * @param $isExport  是否输出excel
	 * @return object/null/array
	 */
	public function getEnrollList($activity_id, $nickname='', $limit=10, $start=0, $order = 'id',$by='desc',$isExport= false){

		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$partake = M('miactivity_partake');
		$miactivity_db = M('miactivity');

		//是否需要审核
		$rel = $miactivity_db
			->where(array('id'=> $activity_id, 'fromCustomerId'=>$cid))
			->find();

		$needCheck = json_decode($rel['jsonstr'], true)['need_check'];
		$isPay = json_decode($rel['jsonstr'], true)['isPay'];
		$actName = $rel['activityname'];

		$map = array();
		$map['p.activityId'] = $activity_id;
		$map['p.cid'] = $cid;
		if(!empty($nickname)){
			$map['e.form_json_str|u.nickname|u.phone'] = array(array('like','%'.$nickname.'%'),array('like','%'.$nickname.'%'),
				array('like','%'.$nickname.'%'),'_multi'=>true);
		}
		if($isExport){
			//输出excel
			$dataExcel = $excelName = $excelMap = array();
			$excelMap['p.activityId'] = $activity_id;
			$excelMap['p.cid'] = $cid;
			$userList = $partake->alias('p')
				->field('p.*, c.name as channel_name, e.id as enrollId, e.form_json_str as formVal, e.charge,e.pay_result_str as payResult, e.payment_status, e.verify_status, u.city, u.openid, u.headimgurl,u.nickname')
				->join('inner join '. C('DB_PREFIX').'mibaoming_info e on p.id = e.partakeId')
				->join('left join '.C('DB_PREFIX').'miactivity_channel c on p.channelId = c.id')
				->join('left join '.C('DB_PREFIX').$cid.'_user_weixin_info u on p.userId = u.userId')
				->where($excelMap)
				->select();

			if($userList){
				foreach($userList as $k=>$val){
					$excelName[$k][] = array('nickname','昵称');
					$excelName[$k][] = array('createTime','报名时间');
					$excelName[$k][] = array('channel_name','来源渠道');
					$dataExcel[$k]['nickname'] = $val['nickname']?$val['nickname']:'未知';
					$dataExcel[$k]['createTime'] = $val['createTime'];
					$dataExcel[$k]['channel_name'] = $val['channel_name']?$val['channel_name']:'未知';
					$formVal = json_decode($val['formVal'], true);
					foreach($formVal as $key=>$value){
						$dataExcel[$k][$value['itemName']] = $value['value'];
						$excelName[$k][] = array($value['itemName'],$value['itemName']);
					}
					if($val['verify_status'] == 0){
						$dataExcel[$k]['verify_status'] = '待审核';
					}elseif($val['verify_status'] == 0){
						$dataExcel[$k]['verify_status'] = '审核成功';
					}else{
						$dataExcel[$k]['verify_status'] = '审核失败';
					}
					$excelName[$k][] = array('verify_status','审核状态');

					if($val['payment_status'] == 0){
						$dataExcel[$k]['payment_status'] = '待付款';
					}elseif($val['payment_status'] == 1){
						$dataExcel[$k]['payment_status'] = '已付款';
					}elseif($val['payment_status'] == 2){
						$dataExcel[$k]['payment_status'] = '退款成功';
					}elseif($val['payment_status'] == 3){
						$dataExcel[$k]['payment_status'] = '退款失败';
					}elseif($val['payment_status'] == 4){
						$dataExcel[$k]['payment_status'] = '无需支付';
					}
					$excelName[$k][] = array('payment_status','支付状态');

				}

				/*echo '<pre>';
				var_dump($dataExcel);
				echo '</pre>';exit;*/
				return array(
					'dataExcel' =>$dataExcel,
					'excelName' => $excelName[0],
					'actName' => $actName
				);
			}
		}else{
			$userList = $partake->alias('p')
				->field('p.*, c.name as channel_name, e.id as enrollId, e.form_json_str as formVal, e.charge,e.pay_result_str as payResult, e.payment_status, e.verify_status, u.city, u.openid, u.headimgurl,u.nickname')
				->join('inner join '. C('DB_PREFIX').'mibaoming_info e on p.id = e.partakeId')
				->join('left join '.C('DB_PREFIX').'miactivity_channel c on p.channelId = c.id')
				->join('left join '.C('DB_PREFIX').$cid.'_user_weixin_info u on p.userId = u.userId')
				->where($map)
				->order($order.' '.$by)
				->limit($start,$limit)
				->select();
		}

		$list = array();
		$total = $partake->alias('p')
			//->field('p.*, c.name as channel_name, e.id as enrollId, e.form_json_str as formVal, e.charge, e.payment_status as status,u.city, u.headimgurl,u.nickname')
			->join('inner join '. C('DB_PREFIX').'mibaoming_info e on p.id = e.partakeId')
			->join('left join '.C('DB_PREFIX').'miactivity_channel c on p.channelId = c.id')
			->join('left join '.C('DB_PREFIX').$cid.'_user_weixin_info u on p.userId = u.userId')
			->where($map)
			->count();

		if($userList){
			foreach($userList as $key=>$val){
				$val['needCheck'] = $needCheck;
				$val['isPay'] = $isPay;
				$list[] = $val;
			}
		}

		Session::switchCustomer($cid);
		if($list){
			Output::instance()->objArray($list, $total);
		}else{
			Output::instance()->resultCode();
		}

	}

	/**
	 * 获取报名人数 参与人数 访问数 渠道统计
	 * @param $activity_id 活动id
	 * @return object/null
	 */

	public function getSummary($activity_id,$isExport=true){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		//如果不需要审核,报名人数查询出状态为0,如果需要审核查询状态1,   参与人数查询所有的
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$miactivity_partake_db = M('miactivity_partake');
		$miactivity_visit_db = M('miactivity_visit');
		$miactivity_db = M('miactivity');
		$enrollTable = M('mibaoming_info');

		//1.查询活动名称
		$rel = $miactivity_db
			->where(array('id'=> $activity_id, 'fromCustomerId'=>$cid))
			->find();
		$activityName = $rel['activityname'];

		//2查询参与人数
		$map = array();
		$map['a.activityId'] = $activity_id;
		$map['a.cid'] = $cid;
		$joinCount = $miactivity_partake_db->alias('a')
			->field('a.*')
			->join('inner join '.C('DB_PREFIX').'mibaoming_info e on a.id=e.partakeId')
			->where($map)
			->count('distinct(a.userId)');

		//3查询报名人数,查询审核状态为1的人数
		$enrollCount = $enrollTable
			->where(array('cid'=>$cid, 'activityId'=>$activity_id, 'verify_status'=>1))
			->count();

		if(!$joinCount){
			$joinCount = 0;
		}
		if(!$enrollCount){
			$enrollCount = 0;
		}
		//4.总浏览数
		$condition = $channel_data_rel = array();
		$channel_data = array();
		$date_data = array();
		$condition['v.cid'] = $cid;
		$condition['v.activityId'] = $activity_id;
		//4.1总浏览人数去重
		$visitCount = $miactivity_visit_db->alias('v')
			->where($condition)
			->count('distinct(userId)');

		if(!$visitCount){
			$visitCount = 0;
		}

		//4.2按日期和渠道进行分类组装
		$visitList = $miactivity_visit_db->alias('v')
			->field('v.*, c.name as channel_name')
			->join('left join '.C('DB_PREFIX').'miactivity_channel c on v.channelId=c.id')
			->where($condition)
			->order('createTime desc')
			->select();
		$partake_map = $date_result= array();
		if($visitCount > 0){
			//按日期分类查询
			foreach($visitList as $key=>$value){
				$date_day = date('Y-m-d', strtotime($value['createTime']));
				$date_data[$date_day]['date_day'] = $date_day;
				$date_data[$date_day]['visit_count'][$value['userId']] = 1;

				//按渠道查询
				if($value['channelId']){
					$channel_data[$value['channelId']]['channel_name'] = $value['channel_name'];
					$channel_data[$value['channelId']]['channel_id'] = $value['channelId'];
					$channel_data[$value['channelId']]['visit_count'][$value['userId']] = 1;
				}
			}

			//对日期进行浏览人数去重,第二次修改参与人数也进行去重
			foreach($date_data as $k=>$value){
				$date_day_t = date('Y-m-d', strtotime($k)+24*60*60);
				$partake_map['cid'] = $cid;
				$partake_map['activityId'] = $activity_id;
				$partake_map['createTime']  = array(array('GT',$k),array('ELT',$date_day_t),'and');
				$partake_count = $miactivity_partake_db
                                    ->where($partake_map)
                                    ->count('distinct(userId)');
				$date_result[$k]['partake_count'] = $partake_count;
				$date_result[$k]['date_day'] = $value['date_day'];
				$date_result[$k]['visit_count'] = count($value['visit_count']);
			}
			//对渠道进行浏览人数去重,第二次修改参与人数也进行去重
			foreach($channel_data as $k=>$val){
				$partake_count = $miactivity_partake_db
					->where(array('cid'=>$cid, 'activityId'=>$activity_id,'channelId'=>$val['channel_id']))
					->count('distinct(userId)');
				$channel_data_rel[$partake_count]['partake_count'] = $partake_count;
				$channel_data_rel[$partake_count]['channel_name'] = $val['channel_name'];
				$channel_data_rel[$partake_count]['channel_id'] = $val['channel_id'];
				$channel_data_rel[$partake_count]['visit_count'] = count($val['visit_count']);
			}
			krsort($channel_data_rel);
		}
		/*echo '<pre>';
		var_dump($date_result);
		echo '</pre>';exit;*/
		$summary_data = array();
		$summary_data['partake_count'] = $joinCount;
		$summary_data['enroll_count'] = $enrollCount;
		$summary_data['visit_count'] = $visitCount;
		$summary_data['channel_data'] = $channel_data_rel;
		$summary_data['date_data'] = $date_result;
		$summary_data['activityname'] = $activityName;

		if($visitList !== null){
			Session::switchCustomer($cid);
			if($isExport==true){
				Output::instance()->object($summary_data);
			}else{
				return $summary_data;
			}

		}else{
			Output::instance()->resultCode();
		}

	}

	/**
	 * 获取用户统计
	 * @param $activity_id 活动id
	 * @return object/null
	 */


	public function getUserSummary($activity_id,$isExport=true){

		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$miactivity_partake_db = M('miactivity_partake');
		$miactivity_visit = M('miactivity_visit');

		$map = array();
		$map['a.activityId'] = $activity_id;
		$map['a.cid'] = $cid;
		$map['a.deleted'] = 0;
		$map['a.userId'] = array('gt',0);
		$list = $miactivity_partake_db->alias('a')
			->field('a.*,d.nickname,d.headimgurl,e.activityname')
			->join('left join '.C('DB_PREFIX').$cid.'_user_weixin_info d  on a.userId=d.userId')
			->join('inner join '.C('DB_PREFIX').'miactivity e on a.activityId=e.id')
			->where($map)
			->order('a.createTime  asc')
			->select();

		$user_data=$user_data_sort=$result= array();
		//var_dump($miactivity_partake_db->getLastSql());

		$condition = array();
		$activityname = '';
		if($list){
			foreach ($list as $key => $value) {
				//对应的分享浏览人数
				$activityname = $value['activityname'];
				$user_data[$value['userId']]['user_info'] = $value;
				$condition['cid'] = $cid;
				$condition['activityId'] = $activity_id;
				$condition['fromUserId'] = $value['userId'];
				$count = $miactivity_visit
					->where($condition)
					->count('distinct(userId)');
				if($count == null){
					$user_data[$value['userId']]['count'] = 0;
				}
				$user_data[$value['userId']]['count'] = $count;
			}
			foreach ($user_data as $k=>$val) {
				$user_data_sort[$k] = $val['count'];
			}
			arsort($user_data_sort);
			foreach($user_data_sort as $k=>$val){
				$result[] = $user_data[$k];
			}
		}

		$summary_data = array();
		$summary_data['user_data'] = $result;
		$summary_data['list_data'] = $list;
		$summary_data['activityname'] = $activityname;
		if($list){
			Session::switchCustomer($cid);
			if($isExport==true){
				Output::instance()->object($summary_data);
			}else{
				return $summary_data;
			}

		}else{
			Output::instance()->resultCode();
		}

	}

	/**
	 * 更改报名状态
	 * @param $activity_id 活动id
	 * @param $enrollId 报名id
	 * @param $status 状态
	 * @return array
	 */

	public function updateEnrollStatus($activity_id, $enrollId, $status){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$enrollTable = M('mibaoming_info');
		$activity_table = M('miactivity');
		Session::switchCustomer($cid);
		//查询openid
		$map = array();
		$map['b.id'] = $enrollId;
		$userInfo = $enrollTable->alias('b')
			->field('u.id as userId, u.userName as openid')
			->join('inner join '.C('DB_PREFIX').'user u on b.userId=u.id')
			->where($map)
			->find();

		//查询用户是否已经存在报名成功的信息
		$isMapEnroll = array();
		$isMapEnroll['cid'] = $cid;
		$isMapEnroll['activityId'] = $activity_id;
		$isMapEnroll['verify_status'] = 1;
		$isMapEnroll['userId'] = $userInfo['userId'];
		$enrollInfo = $enrollTable->where($isMapEnroll)->find();
		// var_dump($enrollInfo);exit;
		if($enrollInfo && ($status == 1)){
			Output::instance()->object(array(
				'code' => -1,
				'message' => '此用户已报名成功!',
				'data' => ''
			));
			return;
		}

		$data = array();
		$data['id'] = $enrollId;
		$data['verify_status'] = $status;
		$bool = $enrollTable->save($data);

		if($bool){
			$activity = $activity_table->where(array('id'=>$activity_id))->find();
			$actPlace = json_decode($activity['jsonstr'], true)['actPlace'];
			$activityName = json_decode($activity['jsonstr'], true)['activityname'];
			$startTime = json_decode($activity['jsonstr'], true)['startTime'];
			$endTime = json_decode($activity['jsonstr'], true)['endTime'];

			$datas = array();
			if($status == 1){
				//审核成功
				$tmpStatus = 'confirmsign';
				$datas['first'] = array('value'=> '活动报名成功!','color'=>"#743A3A");
				$datas['keyword1'] = array('value'=> $activityName,'color'=>'#173177');
				$datas['keyword2'] = array('value'=> $startTime.'-'.$endTime,'color'=>'#173177');
				$datas['keyword3'] = array('value'=> $actPlace,'color'=>'#173177');
				$datas['remark'] = array('value'=> '期待您的光临!',"color"=>'#008000');
			}else{
				//审核失败
				$tmpStatus = 'enrollfail';
				$datas['first'] = array('value'=> '很遗憾,活动报名未审核通过!','color'=>"#743A3A");
				$datas['keyword1'] = array('value'=> $activityName,'color'=>'#173177');
				$datas['keyword2'] = array('value'=> $startTime.'-'.$endTime,'color'=>'#173177');
				$datas['keyword3'] = array('value'=> $actPlace,'color'=>'#173177');
				$datas['remark'] = array('value'=> '感谢您的参与!',"color"=>'#008000');
			}

			//Log::write('报名模板消息:--------------------'.json_encode($datas));
			TemplateMessage::send($userInfo['openid'], $cid,$tmpStatus,'',$datas);
		}

		if($bool){
			Output::instance()->object(array(
				'code' => code_success,
				'message' => '提交成功!',
				'data' => ''
			));
		}else{
			Output::instance()->object(array(
				'code' => -1,
				'message' => '提交失败!',
				'data' => ''
			));
		}
	}

	/**
	 * 报名活动数据导出
	 */
	public function exportEnroll($actId,$type="day"){

		$fileName = '报名活动参与信息' . date('Ymd'); //设置文件名
		switch ($type) {
			case 'day':
					$summary_data = $this->getSummary($actId,false);
					$activity_name = $summary_data['activityname'];
					$expCellName  = array(
						array('date_day','日期'),
						array('partake_count','参与人数'),
						// array('photo_count','照片数'),
						array('visit_count','浏览人数'),
					);
					$expTableData = $summary_data['date_data'];
					$fileName = $activity_name.'_按日期统计_' . date('Ymd');
				break;
			case 'channel':
					$summary_data = $this->getSummary($actId,false);
					$activity_name = $summary_data['activityname'];
					$expCellName  = array(
						array('channel_name','渠道'),
						array('partake_count','参与人数'),
						array('visit_count','浏览人数'),
					);
					$expTableData = $summary_data['channel_data'];
					$fileName = $activity_name.'_按渠道统计_' . date('Ymd');
				break;
			case 'user':
					$summary_user_data = $this->getUserSummary($actId,false);
					$expCellName  = array(
						array('nickname','昵称'),
						array('count','分享浏览次数'),
					);
					$user_data = array();
					$user_data_tmp = $summary_user_data['user_data'];
					foreach ($user_data_tmp as $key => $value) {
						$user_data[$key]['nickname'] = $value['user_info']['nickname'];
						$user_data[$key]['count'] = $value['count'];
					}
					$expTableData = $user_data;
					$fileName = $summary_user_data['activity_name'].'_按用户统计_' . date('Ymd');
				break;
			case 'enroll':
					$enrollListArr = $this->getEnrollList($actId,'', 0, 0, 'id', 'desc', true);
					$expTableData = $enrollListArr['dataExcel'];
					$expCellName = $enrollListArr['excelName'];
					$fileName = $enrollListArr['actName'].'_报名列表_' . date('Ymd');
				break;
			default:
				break;
		}
		$expTableDataTemp = array();
		foreach ($expTableData as $key => $value) {
			$expTableDataTemp[] = $value;
		}
		/*echo '<pre>';
		var_dump($expCellName);
		echo '</pre>';exit;*/
		if($expTableDataTemp){
			Output::instance()->objArrayExcel($fileName,$expCellName,$expTableDataTemp);
		}
	}
}
